$(function(){


    //加载合同项目下拉框
    var coId = $("#coId").val();
    $.ajax({
        url: CONTEXT_PATH + "/contract/getContractListForCombo.do",
        type: "get",
        success: function (data) {
            var themecombo = "";
            if(data.length > 2){
                themecombo = "[{\"text\": \"--请选择--\", \"id\": \"\"},";
                themecombo += data.substring(1);
            }else{
                themecombo = "[{\"text\": \"--请选择--\", \"id\": \"\"}]";
            }
                themecombo = JSON.parse(themecombo);
            $("#contractList").combobox("loadData",themecombo);
            $("#contractList").combobox({
                valueField:'id',
                textField:'text',
                onSelect:function(node){
                    $('#coId').val(node.id);
                }
            });
            $("#contractList").combobox("setValue",coId);
        }
    });

    //初始化动态表格
    $("#activeTableForContractDetail").dyActiveTable({
        idField: 'cdId',
        idFieldWidth: 60,
        index:"序号",
        columns: [
            {field: 'materialName', title: '材料名称', width: 150, height: 30, type: 'text', option: 'required:true,validType:\'length[1,18]\', prompt:\'请输入材料名称\'', class: 'easyui-textbox'},
            {field: 'brand', title: '材料品牌', width: 150, height: 30, type: 'text', option: 'validType:\'length[1,18]\', prompt:\'请输入品牌\'', class: 'easyui-textbox'},
            {field: 'standardType', title: '规格型号', width: 150, height: 30, type: 'text', option: 'required:true,validType:\'length[1,88]\', prompt:\'请输入规格型号\'', class: 'easyui-textbox'},
            {field: 'technicalParameter', title: '技术参数', width: 150, height: 30, type: 'text', option: 'validType:\'length[1,88]\', prompt:\'请输入技术参数\'', class: 'easyui-textbox'},
            {field: 'meteringUnit', title: '计量单位', width: 150, height: 30, type: 'text', option: 'validType:\'length[1,18]\', prompt:\'请输入计量单位\'', class: 'easyui-textbox'},
            {field: 'unitContractPrice', title: '合同单价(元)', width: 150, height: 30, type: 'text', option: 'required:true,validType:[\'floatOrInt\', \'length[1,18]\'], prompt:\'请输入合同单价\'', class: 'easyui-textbox'},
            {field: 'unitPrice', title: '采购单价(元)', width: 150, height: 30, type: 'text', option: 'required:true,validType:[\'floatOrInt\', \'length[1,18]\'], prompt:\'请输入采购单价\'', class: 'easyui-textbox'},
            {field: 'totalCount', title: '工程总量', width: 150, height: 30, type: 'text', option: 'required:true,validType:[\'floatOrInt\', \'length[1,18]\'], prompt:\'请输入工程总量\'', class: 'easyui-textbox'},
            {field: 'totalPrice', isInput: false, calculate: "multiply", calculateColumns: ['unitPrice','totalCount'], title: '合计金额(元)', width: 150, height: 30, type: 'text', class: ''},
            {field: 'remark', title: '备注', width: 150, height: 30, type: 'text', option: 'validType:\'length[1,18]\', prompt:\'请输入备注\'', class: 'easyui-textbox'},
            // {field: 'totalPrice', isInput: false, calculate: "plus", calculateColumns: ['unitPrice','totalCount'], title: '合计金额(元)', width: 150, height: 30, type: 'text', class: ''}
        ]
    });
    
    //保存按钮点击事件
    $('#optionContractDetail').bind('click', function(){
        doOptionContractDetailMethod();
    })

    //模板下载点击事件
    $('#downloadBtn').bind('click', function(){
        downloadTemple();
    })

    //清空按钮点击事件
    $('#emptyTable').bind('click', function(){
        $("#activeTableForContractDetail").dyActiveTable("removeLine");
    })

    //导入确定按钮点击事件
    $('#importBtn').bind('click', function(){
        //获取easyui中的input中的实际的file文件
        var file = $("input[name='importExcel']")[0].files ? $("input[name='importExcel']")[0].files[0] : "noFile";

        //判断是否在IE下而无法获取file
        if(file == "noFile"){
            $.messager.show({ title:'提示', msg: '本功能需要高级浏览器支持,请使用IE11及以上浏览器或其他非IE内核浏览器！', timeout:3000, showType:"slide" });
            return false;
        }
        //判断是否选择文件
        if(!file){
            $.messager.show({ title:'提示', msg: '请选择要上传的文件！', timeout:3000, showType:"slide" });
            return false;
        }
        //判断文件格式
        if(file.name.substring(file.name.lastIndexOf("."), file.name.length) != ".xlsx"){
            $.messager.show({ title:'提示', msg: '文件必须是xlsx类型的！', timeout:3000, showType:"slide" });
            return false;
        }
        readWorkbookFromLocalFile(file, parseData);
    })
});


//初始化导入模板下载
function downloadTemple(){
    var aoa = [
        ['材料名称','材料品牌', '规格型号','技术参数' , '计量单位', '工程总量','合同单价(元)', '采购单价(元)','备注'],
        ['钢材','宝武钢铁', 'gb-121','贵钢', '吨', '2000','300', '6000','宝武制造的高强度钢材'],
        ['水泥','海螺水泥', 'YT-623','贵钢', 'KG', '500','50', '30','海螺水泥制造黄沙水泥']
    ];
    /* build worksheet from the grid data */
    var ws = XLSX.utils.aoa_to_sheet(aoa);

    /* build up workbook */
    var wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, '合同清单');

    if(isIEAll()){
        $.messager.show({ title:'提示', msg: '导入功能需要高级浏览器支持,其他非IE内核浏览器再下载模板进行导入操作！', timeout:3000, showType:"slide" });
        return false;
    }else{
        /* generate download */
        XLSX.writeFile(wb, "合同清单模板.xlsx");
    }
}

//从读取到的excel中取解析数据，插入到表格中
function parseData(workbook){
    var sheetNames = workbook.SheetNames; // 工作表名称集合
    var worksheet = workbook.Sheets[sheetNames[0]]; // 这里我们只读取第一张sheet
    var json = XLSX.utils.sheet_to_json(worksheet);
    action(function(){
        $.messager.progress({
            title: '提示',
            msg: '数据加载中, 请稍候...',
            text: '',
            interval:0
        });
    });
    action(function(json){
        if(json.length == 0){
            action(closeProgress, null, 500);
        }
        for(var i=0; i < json.length; i++){
            setTimeout((function(i, json){
                return function(){
                    var rowData = json[i];
                    var jsonForAdd = {};
                    jsonForAdd["materialName"] = rowData["材料名称"];
                    jsonForAdd["brand"] = rowData["材料品牌"];
                    jsonForAdd["standardType"] = rowData["规格型号"];
                    jsonForAdd["technicalParameter"] = rowData["技术参数"];
                    jsonForAdd["meteringUnit"] = rowData["计量单位"];
                    jsonForAdd["unitContractPrice"] = rowData["合同单价(元)"];
                    jsonForAdd["unitPrice"] = rowData["采购单价(元)"];
                    jsonForAdd["totalCount"] = rowData["工程总量"];
                    jsonForAdd["remark"] = rowData["备注"];
                    var value = ((i + 1) / json.length * 100);
                    action(progressValue, value);
                    var param = [jsonForAdd, true]
                    $("#activeTableForContractDetail").dyActiveTable("addLine", param);
                    if(i == json.length - 1){
                        $("#activeTableForContractDetail").dyActiveTable("sortIndex");
                        action(closeProgress, null, 500);
                    }
                }
            })(i, json),i*100);
        }
    }, json);
}

function action(callback, param, time){
    setTimeout(callback(param), time);
}

/**
 * 更新进度条的显示值
 * @param value
 */
function progressValue(value){
    $.messager.progress("bar").progressbar("setValue", value);
    console.log("progressValue======>" + value);
}

/**
 * 关闭进度的显示
 */
function closeProgress(){
    $("#activeTableForContractDetail").dyActiveTable("removeLine", [1, 1]);
    $.messager.progress('close');
}

// 读取本地excel文件
function readWorkbookFromLocalFile(file, callback) {
    var reader = new FileReader();
    //判断redaer的readAsBinaryString方法是否存在
    if(reader.readAsBinaryString){
        reader.onload = function(e) {
            var data = e.target.result;
            var workbook = XLSX.read(data, {type: 'binary'});
            if(callback) callback(workbook);
        };
        reader.readAsBinaryString(file);
    }else{
        reader.readAsArrayBuffer(file);
        reader.onload = function(e){
            var bytes = new Uint8Array(e.target.result);
            var length = bytes.byteLength;
            var binary = "";
            for (var i = 0; i < length; i++) {
                binary += String.fromCharCode(bytes[i]);
            }
            var base64Str = btoa(binary);
            var workbook = XLSX.read(base64Str, {type: 'base64'});
            if(callback) callback(workbook);
        }.bind(this);
    }
}

/**
 * 执行保存操作方法
 */
function doOptionContractDetailMethod(){
    var params = $("#operate_form").serialize();
    $("#operate_form").form("submit",{
        cache:false,
        data: params,
        url: CONTEXT_PATH + "/contractDetail/addSave.do",
        onSubmit:function() {
            var flag = $(this).form("validate");
            if(flag){
                preventSubmit(null, "optionContractDetail");
            }
            return flag;
        },
        success:function(data) {
            var obj = JSON.parse(data);
            var url = CONTEXT_PATH + "/contractDetail/index.do";
            saveJump(obj,url);
        }
    });
}